package com.rybbaby.tss.front.tssClasses.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.consts.RoleConsts;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.core.web.service.IViewService;
import com.rybbaby.tss.front.tssClasses.entity.*;
import com.rybbaby.tss.front.tssClasses.service.ITssClassesService;
import com.rybbaby.tss.front.tssClasses.service.ViewTssClassAttendanceExportService;
import com.rybbaby.tss.front.tssClasses.service.ViewTssClassChangeService;
import com.rybbaby.tss.front.tssClassesLessons.entity.TssClassesLessons;
import com.rybbaby.tss.front.tssClassesLessons.service.ITssClassesLessonsService;
import com.rybbaby.tss.front.tssMemberAttendClassRecord.service.ITssMemberAttendClassRecordService;
import com.rybbaby.tss.front.tssStudent.entity.TssStudent;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;


/**
 * @author 雷春琼
 * @description 班级表管理
 * @createDate 2017-08-09 下午11:50:14
 */
@Controller
@RequestMapping(value = "tssClassesController")
public class TssClassesController extends BaseController {

    @Autowired
    private ITssClassesService tssClassesService;
    @Autowired
    private ITssClassesLessonsService tssClassesLessonsService;
    @Autowired
    private IViewService<ViewTssClassRoster> viewService;
    @Autowired
    private ViewTssClassChangeService viewTssClassChangeService;
    @Autowired
    private ViewTssClassAttendanceExportService viewTssClassAttendanceExportService;
    @Autowired
    private ISysAdminUserService sysAdminUserService;

    @Autowired
    private ITssMemberAttendClassRecordService tssMemberAttendClassRecordService;


    /**
     * 获取班级表列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取班级表列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssClassesList", method = RequestMethod.POST)
    public ModelAndView tssClassesList(TssClasses entity, PageBean paramPageBean, @RequestParam(required = false) Integer type) {
        ModelAndView mav = null;
        try {
            if (type == 1) {
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssClassesListView"));
            } else if (type == 2) {
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitClassesListView"));
            }
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(TssClasses.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            String ids = "";
            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();
            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
            //获取当前登录者所拥有角色
            List<String> roleList = super.getLoginAdminRoles();
            //老师只能看到所属老师是自己的
            if (roleList.contains(RoleConsts.TSS_TEACHER)) {
                dc.add(Restrictions.or(Restrictions.sqlRestriction(" adminUserId ='" + adminUserId + "'"),
                        Restrictions.sqlRestriction(" empAdminUserId ='" + adminUserId + "'")));
            } else {
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
            }

            dc.add(Restrictions.eq("type", type));
            dc.addOrder(Order.desc("updateTime"));
            PageBean pageBean = tssClassesService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 获取亲子班级表列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取亲子班级表列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "classAttendance", method = RequestMethod.POST)
    public ModelAndView classAttendance(ViewClassesAttendanceManagement entity, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("ViewClassesAttendanceManagementView"));
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            String classTime_end = getParameter("classTime_end");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (classTime_end != null && !classTime_end.equals("")) {

            } else {
                Calendar lastDate = Calendar.getInstance();
                lastDate.add(Calendar.DAY_OF_YEAR, 0);
                String tomorrow = sdf.format(lastDate.getTime());
                unLockMap.put("classTime_end", new String[]{tomorrow});
            }
            DetachedCriteria dc = DetachedCriteria.forClass(ViewClassesAttendanceManagement.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            dc.add(Restrictions.eq("type", 1));
            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();
            SysAdminUser user = super.getLoginUser();
            String ids = "";
            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
            //获取当前登录者所拥有角色
            List<String> roleList = super.getLoginAdminRoles();

            if (roleList.contains(RoleConsts.TSS_COUNSELOR) || roleList.contains(RoleConsts.TSS_TEACHER)) {
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + adminUserId + "') "));
            } else {
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
            }
            //dc.addOrder(Order.desc("viewClassesAttendanceManagementKey.createTime"));
            dc.addOrder(Order.desc("classTime"));
            PageBean pageBean = tssClassesService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("type", 1);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 获取过渡班级表列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取过渡班级表列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "transitionClassAttendance", method = RequestMethod.POST)
    public ModelAndView transitionClassAttendance(ViewClassesAttendanceManagement entity, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("ViewTransitionClassAttendanceManagementView"));
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            String classTime_end = getParameter("classTime_end");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (classTime_end != null && !classTime_end.equals("")) {

            } else {
                Calendar lastDate = Calendar.getInstance();
                lastDate.add(Calendar.DAY_OF_YEAR, 0);
                String tomorrow = sdf.format(lastDate.getTime());
                unLockMap.put("classTime_end", new String[]{tomorrow});
            }
            DetachedCriteria dc = DetachedCriteria.forClass(ViewClassesAttendanceManagement.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            dc.add(Restrictions.eq("type", 2));
            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();
            String ids = "";
            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
            //获取当前登录者所拥有角色
            List<String> roleList = super.getLoginAdminRoles();

            if (roleList.contains(RoleConsts.TSS_COUNSELOR) || roleList.contains(RoleConsts.TSS_TEACHER)) {
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + adminUserId + "') "));
            } else {
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
            }
            //dc.addOrder(Order.desc("viewClassesAttendanceManagementKey.createTime"));
            PageBean pageBean = tssClassesService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("type", 2);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 转到编辑视图
     *
     * @param entity       接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到班级表视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(TssClasses entity, @RequestParam(required = true) String serializeNum, @RequestParam(required = true) String tssClassType) {
        ModelAndView mav = null;
        Integer type = Integer.valueOf(tssClassType);
        // Integer  type=1;
        if (entity != null && entity.getId() != null) {
            if (type == 1) {

                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssClassesEditChangeView"));
            } else if (type == 2) {
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitClassesEditChangeView"));
            }
            TssClasses editEntity = this.tssClassesService.get(entity.getId());
            List<Map<String, Object>> classesMapList = tssClassesService.batchQueryById(entity.getId());
            for (Map<String, Object> classesMap : classesMapList) {
                List<Map<String, Object>> lessonsList = this.tssClassesLessonsService.getListByClassId(classesMap.get("id").toString());
                classesMap.put("lessonsList", lessonsList);
            }
            mav.addObject("listMap", classesMapList);
            mav.addObject("editEntity", editEntity);
            mav.addObject("editModel", "edit");
        } else {
            if (type == 1) {
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssClassesEditView"));
            } else if (type == 2) {
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitClassesEditView"));

            }
            mav.addObject("editModel", "add");
        }
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 保存编辑的对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存班级表对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(TssClasses entity) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            String lessonsObject = request.getParameter("lessonsObject");
            String startTimes = request.getParameter("startTimes");
            String endTimes = request.getParameter("endTimes");
            entity.setStartTime(new Time(sdf.parse(startTimes).getTime()));
            entity.setEndTime(new Time(sdf.parse(endTimes).getTime()));
            entity.setAdminUserId(super.getLoginUser().getId());

            //解析课节json
            Gson gson = new Gson();
            List<TssClassesLessons> classesLessonsList = gson.fromJson(lessonsObject, new TypeToken<List<TssClassesLessons>>() {
            }.getType());
            //首先判断该时间是否有老师上课，教室被占用
            StringBuffer buf = new StringBuffer();
            for (TssClassesLessons classesLessons : classesLessonsList) {
                String time = classesLessons.getClassTime().toString();
//                Date f = new Date(time);
                LocalDate f=LocalDate.now();
                String c = new SimpleDateFormat("yyyy-MM-dd").format(f);
                buf.append(c + ",");
            }
            String ss[] = StringUtils.split(buf.toString(), ",");
            String classTime = StringUtils.join(ss, "','");
            String sql = "select * from tss_class_lessons where  (startTime BETWEEN ? and ? or endTime   BETWEEN ? and ?) and\n" +
                    " classTime in ('" + classTime + "')  and roomId = ? and adminUserId = ? GROUP BY classTime";
            List<Map<String, Object>> listMap = this.tssClassesLessonsService.findForJdbc(sql, new Object[]{entity.getStartTime(), entity.getEndTime(), entity.getStartTime(), entity.getEndTime(), entity.getRoomId(), entity.getEmpAdminUserId()});

            if (listMap.size() > 0) {
                ajr.setResCode(302);
                ajr.setResMsg("保存失败!");
                ajr.setData(listMap);
                return ajr.jsonResponse(true);
            }

            //判断班级属于哪个学期类型
//            Date date = new Date(entity.getStartDate().toString());
//            String year = new SimpleDateFormat("yyyy").format(date);
            LocalDate date=LocalDate.parse(entity.getStartDate().toString());
            int year=date.getYear();
            String semesterSql = "select * from tss_semester ts LEFT join sys_admin_user sau on sau.id=ts.adminUserId \n" +
                    "  where (ts.startDate  BETWEEN ? and ? or ts.endDate BETWEEN  ? and ?) and ts.particularYear=? \n" +
                    " and sau.schoolId=? ";
            List<Map<String, Object>> semesterMap = this.tssClassesLessonsService.findForJdbc(semesterSql, new Object[]{entity.getStartDate(), entity.getEndDate(), entity.getStartDate(), entity.getEndDate(),
                    year, super.getLoginUser().getSchoolId()});
            if (semesterMap.size() ==1) {
             entity.setSemester(Integer.parseInt(semesterMap.get(0).get("type").toString()));
            }

            Boolean bool = this.tssClassesService.saveOrUpdate(entity, lessonsObject);
            if (bool) {
                ajr.setResCode(200);
                ajr.setResMsg("保存成功!");
            } else {
                ajr.setResCode(301);
                ajr.setResMsg("保存失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 日期对调
     *
     * @param
     * @return
     */
    @RequestLog(content = "转到客户表视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "switchDate", method = RequestMethod.GET)
    public ModelAndView Jump(TssStudent entity) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("switchDateView"));

        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                this.tssClassesService.deleteEntityById(id);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                boolean batchDelete = this.tssClassesService.batchDelete(ids.split(","));
                if (!batchDelete) {
                    ajr.setResMsg("删除失败!");
                    ajr.setResCode(302);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 跳转报班选择班级页面
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "跳转报班选择班级页面", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssAttendClassesList", method = RequestMethod.POST)
    public ModelAndView tssAttendClassesList(TssClasses entity, PageBean paramPageBean, @RequestParam(required = true) Integer type, @RequestParam(required = true) String memberPackageId) {
        ModelAndView mav = null;
        try {
            if (type == 1) {
                //亲子报班选择班级列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberAttendClassListView"));
            } else if (type == 2) {
                //过渡报班选择班级列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitMemberAttendClassListView"));
            }
            mav = getMayChooseAttendClassList(mav, entity, paramPageBean, type);
            mav.addObject("memberPackageId", memberPackageId);
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 跳转转班选择班级页面
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "跳转转班选择班级页面", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssChangeClassesList", method = RequestMethod.POST)
    public ModelAndView tssChangeClassesList(TssClasses entity, PageBean paramPageBean, @RequestParam(required = false) String memberPackageId, @RequestParam(required = true) String targetDataId, @RequestParam(required = false) Integer type) {
        ModelAndView mav = null;
        try {
            if (type == 1) {
                //亲子转班选择班级列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberChangeClassListView"));
            } else if (type == 2) {
                //过渡转班选择班级列表
                //mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberChangeClassListView"));
            }
            mav = getMayChooseAttendClassList(mav, entity, paramPageBean, type);
        } catch (Exception e) {
            throw e;
        }
        mav.addObject("memberPackageId", memberPackageId);
        if (targetDataId != null) {
            mav.addObject("targetDataId", targetDataId);
        }
        return mav;
    }


    public ModelAndView getMayChooseAttendClassList(ModelAndView mav, TssClasses entity, PageBean paramPageBean, Integer type) {
        Map<String, String[]> unLockMap = getParameterMap(request);
        DetachedCriteria dc = DetachedCriteria.forClass(TssClasses.class);


        dc.add(Restrictions.eq("type", type));

        //获取当前登录者
        String adminUserId = super.getLoginUser().getId();
        String ids = "";
        SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
        List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
        ids = StringUtils.join(idsList, "','");
        dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
        dc.addOrder(Order.desc("createTime"));
        HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
        PageBean pageBean = tssClassesService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
        mav.addObject(super.SEARCH_MAP, unLockMap);
        mav.addObject(super.PAGE_BEAN, pageBean);
        mav.addObject("searchFormId", SEARCH_FORM);
        mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
        mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
        return mav;
    }


    /**
     * 根据班级id查询会员详情
     *
     * @param classId
     * @return
     */
    @RequestLog(content = "根据班级id查询会员详情", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getListByClassId", method = RequestMethod.GET)
    public ModelAndView getListByClassId(@RequestParam(required = true) String classId, @RequestParam(required = true) Integer classType) {
        ModelAndView mav = null;
        if (classType == 1) {
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssClassesDetailListView"));
        } else if (classType == 2) {
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitClassesDetailListView"));
        }
        List<Map<String, Object>> classesMapList = new ArrayList<>();
        if (StringUtils.isNotBlank(classId)) {
            classesMapList = tssClassesService.batchQueryById(classId);
            for (Map<String, Object> classesMap : classesMapList) {
                List<Map<String, Object>> lessonsList = this.tssClassesLessonsService.getListByClassId(classesMap.get("id").toString());
                classesMap.put("lessonsList", lessonsList);
            }
        }
        mav.addObject("listMap", classesMapList);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 获取班级花名册
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取班级花名册", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getClassRosterById", method = RequestMethod.POST)
    public ModelAndView getClassRosterById(ViewTssClassRoster entity, PageBean paramPageBean, @RequestParam(required = true) String classId, @RequestParam(required = true) Integer classType) {
        ModelAndView mav = null;
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(ViewTssClassRoster.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            dc.add(Restrictions.eq("classType", classType));
            dc.add(Restrictions.eq("classId", classId));
            if (classType == 1) {
                //亲子班级花名册
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssClassesRosterListView"));
            } else if (classType == 2) {
                //过渡班级花名册
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitClassesRosterListView"));
            }

            PageBean pageBean = viewService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");

        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 获取班级变更
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取班级变更", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getClassChangeById", method = RequestMethod.POST)
    public ModelAndView getClassChangeById(ViewTssClassRoster entity, PageBean paramPageBean, @RequestParam(required = true) String classId, @RequestParam(required = true) Integer classType) {
        ModelAndView mav = null;
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(ViewTssClassRoster.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            dc.add(Restrictions.eq("classType", classType));
            dc.add(Restrictions.eq("classId", classId));
            if (classType == 1) {
                //亲子班级变更
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssClassesChangeView"));
            } else if (classType == 2) {
                //过渡班级变更
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitClassesChangeView"));
            }
            List<Map<String, Object>> classesMapList = new ArrayList<>();
            if (StringUtils.isNotBlank(classId)) {
                classesMapList = tssClassesService.batchQueryById(classId);
                for (Map<String, Object> classesMap : classesMapList) {
                    List<Map<String, Object>> lessonsList = this.tssMemberAttendClassRecordService.findCouldClassLessonInfoByClassIdAndMemberPackageId(classesMap.get("id").toString());
                    classesMap.put("lessonsList", lessonsList);
                }
            }
            mav.addObject("listMap", classesMapList);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");

            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");

        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @RequestLog(content = "导出", save = true)
    @Token(validateToken = false)
    @ResponseBody
    @RequestMapping("/exportExcle")
    public void exportExcle(Integer type, String ids, HttpServletResponse response, HttpServletRequest request) {
        System.out.println(ids);
        String path = "jso/export_classes.json";
        String templateName = request.getParameter("templateName");
        List<ViewClassesChange> classesList = null;

        /*优先判断是否选择序号（ids）
        如果序号未选择 当标识符为 1 的时候 根据标识条件导出 标识为 0 时 默认导出所有数据*/

        if (ids == "") {
            classesList = viewTssClassChangeService.getAllClassList(type);
        }
        //如果选择了序号 则根据序号导出该信息
        if (ids != "") {
            List<String> strings = Arrays.asList(ids.split(","));
            classesList = viewTssClassChangeService.findByIds(strings);
        }
        ExportUtil e = new ExportUtil();
        e.export(path, templateName, classesList, request, response);
    }

    /**
     * 客户管理>客户名单导出
     * 杨然
     */
    @RequestLog(content = "导出", save = true)
    @Token(validateToken = false)
    @ResponseBody
    @RequestMapping("/classExportExcle")
    public void classExportExcle(Integer typ, Integer flag, String ids, PageBean paramPageBean, ViewClassesAttendanceManagementExport entity, HttpServletResponse response, HttpServletRequest request) {
        String path = "jso/export_classesAttendanceManagement.json";
        List<ViewClassesAttendanceManagementExport> classList = null;
        String templateName = request.getParameter("templateName");

        if (ids != "") {
            classList = viewTssClassAttendanceExportService.findListByIds(Arrays.asList(ids.split(",")));
        }
        if (ids == "") {

            if (flag == 1) {
                Map<String, String[]> unLockMap = getParameterMap(request);
                DetachedCriteria dc = DetachedCriteria.forClass(ViewClassesAttendanceManagementExport.class);
                HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
                dc.add(Restrictions.eq("type", typ));
                PageBean pageBean = tssClassesService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
                classList = (List<ViewClassesAttendanceManagementExport>) pageBean.getList();
            } else {
                classList = viewTssClassAttendanceExportService.getAllList(typ);
            }

        }

        ExportUtil e = new ExportUtil();
        e.export(path, templateName, classList, request, response);
    }

    /**
     * 停用,恢复班级
     *
     * @param targetDateId
     * @param isBlockUp
     * @return
     */
    @ResponseBody
    @RequestLog(content = "停用,恢复班级", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "updateStaffByIsBlockUp", method = RequestMethod.POST)
    public String updateStaffByIsBlockUp(@RequestParam(required = true) String targetDateId, @RequestParam(required = true) Boolean isBlockUp) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            Integer status = this.tssClassesService.updateClassByIsBlockUp(targetDateId, isBlockUp);
            if (status == null) {
                ajr.setResMsg("修改失败!");
                ajr.setResCode(302);
            } else {
                ajr.setResMsg("修改成功!");
                ajr.setResCode(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("修改失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(true);

    }

    /**
     * 验证班级名称不可重复
     *
     * @param name 课时包
     * @return
     */
    @ResponseBody
    @RequestLog(content = "验证班级名称不可重复", save = true)
    @RequestMapping(value = "verificationClassName", method = RequestMethod.POST)
    public String verificationClassName(String name) {
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("select * from tss_classes tc left join sys_admin_user sau on sau.id=tc.adminUserId  and type=2 \n" +
                    "where sau.schoolId=? and tc.`name`=?");
            Map<String, Object> findOneForJdbc = sysAdminUserService.findOneForJdbc(sql.toString(), new Object[]{name, super.getLoginUser().getSchoolId()});
            return responseRemoteValidate(findOneForJdbc != null && !findOneForJdbc.isEmpty() && findOneForJdbc.containsKey("count") && (findOneForJdbc.get("count").toString()).equals("0"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据班级开始时间，结束时间，上课时间，下课时间，教室，老师，周几上课 校验班级是否课时创建
     *
     * @param startDate
     * @param endDate
     * @param startTime
     * @param endTime
     * @param roomId
     * @param weekDay
     * @param empAdminUerId
     * @return
     */
    @ResponseBody
    @RequestLog(content = "校验班级是否可以创建", save = true)
    @RequestMapping(value = "verificationClass", method = RequestMethod.POST)
    public String verificationClass(String startDate, String endDate, String startTime, String endTime, String roomId, String weekDay, String empAdminUerId, Integer type) {
        try {
            String schoolId = super.getLoginUser().getSchoolId();
            StringBuffer sql = new StringBuffer();
            Map<String, Object> findOneForJdbc = this.tssClassesService.verificationClass(startDate, endDate, startTime, endTime, roomId, weekDay, empAdminUerId, schoolId, type);
            return responseRemoteValidate(findOneForJdbc != null && !findOneForJdbc.isEmpty() && findOneForJdbc.containsKey("count") && (findOneForJdbc.get("count").toString()).equals("0"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}